<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-select
          clearable
          v-model="dataForm.projectId"
          placeholder="所属项目"
        >
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="dataForm.company"
          placeholder="车辆所属公司"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="dataForm.carCode"
          placeholder="车牌号码"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="dataForm.name"
          placeholder="司机姓名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select clearable v-model="dataForm.status" placeholder="GPS状态">
          <el-option label="未绑定" :value="0" />
          <el-option label="在线" :value="1" />
          <el-option label="离线" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          clearable
          v-model="dataForm.transportStatus"
          placeholder="车辆状态"
        >
          <el-option label="未运输" :value="0" />
          <el-option label="运输中" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList('query')">查询</el-button>
        <el-button  v-if="isAuth('sys:bcarmanagement:mucktruck')" type="danger" @click="synchronous()">同步</el-button>
        <el-button
          v-if="isAuth('sys:bcarmanagement:save')"
          type="primary"
          @click="addOrUpdateHandle()"
          >新增</el-button
        >
        <el-button
          v-if="isAuth('sys:bcarmanagement:delete')"
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
        <el-button
          v-if="isAuth('sys:bcarmanagement:unbinding')"
          type="danger"
          @click="unbindHandle()"
          :disabled="canBatchUnbind"
          >批量解绑</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="company"
        header-align="center"
        align="center"
        label="车辆所属公司"
      >
      </el-table-column>
      <el-table-column
        prop="carCode"
        header-align="center"
        align="center"
        label="车牌号码"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="司机姓名"
      >
      </el-table-column>
      <el-table-column
        prop="telephone"
        header-align="center"
        align="center"
        label="司机联系方式"
      >
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="GPS状态"
      >
        <template slot-scope="scope">
          {{
            scope.row.status === 0
              ? "未绑定 "
              : scope.row.status === 1
              ? "在线"
              : scope.row.status === 2
              ? "离线"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="identifying"
        header-align="center"
        align="center"
        label="GPS设备标识"
      >
      </el-table-column>
      <el-table-column
        prop="projectName"
        header-align="center"
        align="center"
        label="所属项目"
      >
      </el-table-column>
      <el-table-column
        prop="transportStatus"
        header-align="center"
        align="center"
        label="车辆状态"
      >
        <template slot-scope="scope">
          {{
            scope.row.transportStatus === 0
              ? "未运输 "
              : scope.row.transportStatus === 1
              ? "运输中"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            v-if="isAuth('sys:bcarmanagement:update')"
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.id)"
            >修改</el-button
          >
          <el-button
            v-if="isAuth('sys:bcarmanagement:delete')"
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
          <el-button
            v-if="
              isAuth('sys:bcarmanagement:binding') && scope.row.status === 0
            "
            type="text"
            size="small"
            @click="bindHandle(scope.row)"
            >绑定</el-button
          >
          <el-button
            v-if="
              isAuth('sys:bcarmanagement:unbinding') && scope.row.status !== 0
            "
            type="text"
            size="small"
            @click="unbindHandle(scope.row.identifying)"
            >解绑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageParams.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageParams.limit"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>

    <!-- 绑定 -->
    <el-dialog
      title="绑定GPS"
      :close-on-click-modal="false"
      :visible.sync="gpsVisible"
      width="20%"
    >
      <el-form
        :model="gpsForm"
        :rules="gpsRule"
        ref="gpsForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="90px"
      >
        <el-form-item label="GPS" prop="identifying">
          <el-select
            style="width:100%"
            v-model="gpsForm.identifying"
            placeholder="请选择GPS"
          >
            <el-option
              v-for="item in gpsList"
              :key="item.identifying"
              :label="item.identifying"
              :value="item.identifying"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="gpsVisible = false">取消</el-button>
        <el-button type="primary" @click="bindGps">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from "./slagTruck-add-or-update";
export default {
  data() {
    return {
      options: [],
      dataForm: {
        projectId: "",
        company: "",
        carCode: "",
        name: ""
      },
      dataList: [],
      pageParams: {
        page: 1,
        limit: 10
      },
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      gpsForm: {
        identifying: ""
      },
      gpsList: [],
      gpsRule: {
        identifying: [
          { required: true, message: "GPS不能为空", trigger: "change" }
        ]
      },
      gpsVisible: false,
      gpsOther: {},
      projectList: [],
      canBatchUnbind: true
    };
  },
  components: {
    AddOrUpdate
  },
  mounted() {
    this.getProject();
  },
  activated() {
    if (Object.keys(this.$route.query).length == 0) {
      this.getDataList();
    } else {
      this.dataForm.projectId = this.$route.query.projectId;
      this.dataForm.carCode=this.$route.query.carCode; //获取号牌
      this.$nextTick(()=>{
        this.getDataList();
      })
    }
    this.getGpsList();
  },
  methods: {
    // 获取所属项目
    getProject() {
      this.$http({
        url: this.$http.adornUrl(`/sys/project/management/list`),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.projectList = data.list;
        }
      });
    },
    // 获取GPS ls
    getGpsList() {
      this.$http({
        url: this.$http.adornUrl(`/sys/gps/management/list`),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.gpsList = data.list;
        }
      });
    },
    // 获取数据列表
    getDataList(flag) {

      if (flag) {
        this.pageParams.page = 1
      }
      let params = { ...this.pageParams, ...this.dataForm };
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sys/car/management/page"),
        method: "get",
        params: this.$http.adornParams(params)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageParams.limit = val;
      this.pageParams.page = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageParams.page = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      if (val.length > 0) {
        let unbind = val.every(item => {
          return item.status !== 0;
        });
        if (unbind) {
          this.canBatchUnbind = false;
        } else {
          this.canBatchUnbind = true;
        }
      } else {
        this.canBatchUnbind = true;
      }

      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/sys/car/management/delete"),
          method: "delete",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },

    //绑定
    bindHandle(row) {
      console.log(row);
      this.gpsVisible = true;
      this.$nextTick(() => {
        this.$refs["gpsForm"].resetFields();
        this.gpsOther = {
          carCode: row.carCode,
          name: row.name,
          telephone: row.telephone,
          projectId: row.projectId,
          operationType: 0,
          unFlag: "pc"
        };
      });
    },

    bindGps() {
      let params = { ...this.gpsForm, ...this.gpsOther };

      this.$refs["gpsForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/sys/car/management/binding"),
            method: "delete",
            data: this.$http.adornData(params, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.gpsVisible = false;
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },

    //解绑
    unbindHandle(id) {
      let params = {}
      if (id) {
        params = {
            arr: [
              {
                identifying: id
              }
            ],
            unFlag: "pc"
          }
      }else {
        params.arr = this.dataListSelections.map(item => {
            return {
              identifying: item.identifying,

            };
          });
          params.unFlag = 'pc'
      }

      this.$confirm(`确定对车辆进行解绑操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl("/sys/car/management/unbinding"),
          method: "delete",
          data: this.$http.adornData(params, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },

    // 同步
    synchronous() {
      this.$confirm(
        `确定要进行同步操作吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/sys/car/management/mucktruck"),
          method: "get"
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "同步成功",
              type: "success",
              duration: 1500
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    }
  }
};
</script>
